#include "accelmanager.h"

AccelManager::AccelManager()
{
    accelerometer = new QFile("/dev/input/event3");
	activated = false;
	threshold = 5;
}

AccelManager::~AccelManager()
{
    stop();
}
void AccelManager::run()
{
	qDebug() << "accelManager running...";
	Event event;
	indicator = 0;
	activated = true;
	bool init = false;
	currentState = UNKNOWN;
	if (!accelerometer->open(QIODevice::ReadOnly)){
        	qDebug() << "Accelerometer cannot be read";
			currentState = UP;
			return;
    	}
	// init state
	qDebug() << "accelManagenr initialsing...";
	while (!init) {
		event.code = -1;
		while (event.code != 2) { // read correct event
			if (readEvent((char*)&event) != sizeof(Event)) {
				qDebug() << "No data from accelerometer";
			}
		}
		//qDebug() << "accel value:" << event.value;
		if (event.value < 0) {
			indicator--;
		} else if (event.value > 0) {
			indicator++;
		}
		if (updateState()) {
			init = true;
			break;
		}
	}
	qDebug() << "Done!!";
	//===== monitering state =======================
	indicator = 0;
	while (activated) {		
		event.code = -1;
		while (event.code != 2) { // read correct event
			if (readEvent((char*)&event) != sizeof(Event)) {
				qDebug() << "No data from accelerometer";
			}
		}
		//qDebug() << "value" << event.value;
		if (event.value < 0) { // facing down
			indicator--;
		} else if (event.value > 0) { // facing up
			indicator++;
		}

		if (updateState()) {
			indicator = 0;
			emit stateChangeSignal(currentState);
		}
		//msleep(50);
	}
	//===============================================
	accelerometer->close();
}

bool AccelManager::updateState()
{
	//qDebug() << "indicator:" << indicator;
	if (indicator >= threshold) {
		indicator = 0;
		if (currentState != UP) {
			currentState = UP;
			qDebug() << "Facing UP";
			return true;
		}
	} else if (indicator <= (-1*threshold)) {
		indicator = 0;
		if (currentState != DOWN) {
			currentState = DOWN;
			qDebug() << "Facing DOWN";
			return true;
		}
	}
	return false;
}

void AccelManager::stop()
{
	activated = false;
}

/**
 * Read specified number of bytes into a buffer from accelerometer.
 * @return number of bytes readed if succeed, otherwise return -1.
 */
int AccelManager::readEvent(char *buffer)
{
	int byteReaded = 0;
	// keep reading until the buffer is filled with event
	while (byteReaded != sizeof(Event)) { 
		int count = accelerometer->read(buffer+byteReaded,
				sizeof(Event)-byteReaded);
		if (count < 0)	return -1; // failed to read
		if (count == 0) return byteReaded; // no more data to read
		byteReaded += count;
	}
	return byteReaded;
}

int AccelManager::getCurrentState()
{
	return currentState;
}

void AccelManager::stateChangeListener(int state)
{
	qDebug() << "receive stateChangeSignal" << state;
	if (currentState != state) {
		emit stateChangeSignal(state);
	}
}







